var app = getApp();
import api from '../../../services/api'
Page({
  data: {
    buttonBounding: app.globalData.buttonBounding,
    isShowNoData: false,
    keyWord: "",
    baseInfo: {},
    list: [],
    stars: []
  },
  onLoad: function (option) {
    let _that = this
    if (option.phone) {
      this.setData({
        keyWord: option.phone,
      }, function() {
        _that.queryWarrantyInfo();
      })
    }
    // 初始化星空背景
    this.initStars();
  },
  onShow() {
    // 每次显示页面时重新生成星空
    this.initStars();
  },
  // 初始化星空背景动画
  initStars() {
    const stars = [];
    const starCount = 50; // 星星数量
    
    for (let i = 0; i < starCount; i++) {
      stars.push({
        left: Math.random() * 100,
        top: Math.random() * 100,
        delay: Math.random() * 3,
        size: Math.random() * 6 + 2 // 2-8rpx
      });
    }
    
    this.setData({ stars });
  },
  goBack() {
    wx.navigateBack();
  },
  bindconfirm(e) {
    this.setData({
      keyWord: e.detail.value,
    });
    // 回车直接查询
    if (e.detail.value.trim()) {
      this.queryWarrantyInfo();
    }
  },
  bindinput(e) {
    this.setData({
      keyWord: e.detail.value,
    });
    // 如果输入为空，隐藏无数据提示
    if (!e.detail.value.trim()) {
      this.setData({ isShowNoData: false });
    }
  },
  async queryWarrantyInfo() {
    const { keyWord } = this.data;
    
    // 输入验证
    if (!keyWord.trim()) {
      wx.showToast({
        title: '请输入查询信息',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    // 显示加载中
    wx.showLoading({
      title: '查询中...',
      mask: true
    });
    
    try {
      const res = await api.warranty.queryWarrantyInfo({ phone: keyWord });
      wx.hideLoading();
      
      if (res.status == 200) {
        this.setData({ isShowNoData: false });
        
        if (res.data.length > 1) {
          this.setData({ list: res.data });
          wx.navigateTo({ url: "/pages/warranty/list/index" });
        } else {
          // 直接使用质保ID跳转到结果页面
          const warrantyId = res.data[0].warrantyId || res.data[0].id;
          if (warrantyId) {
            wx.navigateTo({ 
              url: `/pages/warranty/result/index?warrantyId=${warrantyId}` 
            });
          } else {
            console.error('质保数据中缺少ID字段:', res.data[0]);
            wx.showToast({
              title: '数据异常，请联系客服',
              icon: 'none',
              duration: 2000
            });
          }
        }
      } else {
        this.setData({ isShowNoData: true });
        // 震动反馈
        wx.vibrateShort();
      }
    } catch (error) {
      wx.hideLoading();
      console.error('查询失败:', error);
      wx.showToast({
        title: '查询失败，请重试',
        icon: 'none',
        duration: 2000
      });
    }
  },
  
  // 添加触觉反馈
  onButtonTap() {
    wx.vibrateShort();
  },
  
  // 清空输入
  clearInput() {
    this.setData({ 
      keyWord: '',
      isShowNoData: false 
    });
  }
});
